import { createSlice} from "@reduxjs/toolkit"

const cartCount = createSlice({
 name:"counter",
 initialState:{
  list:[
    
  ],
  allcheck:false
 },
 reducers:{

    setcheck:(state,val)=>{
        let ls = [...state.list] 
        let idx = ls.findIndex((item)=>item._id === val.payload) 
        ls[idx].check =!ls[idx].check
        state.list = ls
        state.allcheck=state.list.every(i=>i.check)
    },
    setallcheck:(state,val)=>{
        state.allcheck=val.payload
        state.list.forEach(i=>i.check=val.payload)
    },
    setnum:(state,val)=>{
        let ls = [...state.list] 
        let idx = ls.findIndex((item)=>item._id === val.payload._id) 
        ls[idx].num = val.payload.num
        state.list = ls
    }, addcart:(state,val)=>{
      if(state.list.find(i=>i._id == val.payload._id)){//存在购物车就不能添加
        state.list.find(i=>i._id == val.payload._id).num += val.payload.num
        return
      }
      state.list = [...state.list,{...val.payload,check:false}]
      console.log(state.list);
  }

  
 }
})

export const { setcheck,setallcheck,setnum,addcart }  =cartCount.actions

export default cartCount

